import { Component, OnInit, ViewChild, ElementRef, Injector, inject } from '@angular/core';
import { FormGroup, FormControl, FormArray, FormBuilder, Validators } from '@angular/forms';
import * as marked from 'marked';
import { WebMessageService } from '../../services/web-message.service';
import { AdminService, AdminModel } from 'app/modules/admin-manager/services/admin.service';
import { MySelection } from 'app/modules/base/selection';
import { markAllAsTouched, formGroupToFormData } from 'app/modules/base/helper';
import { extend } from 'webdriver-js-extender';
import { AddBase } from 'app/modules/base/add-base';

@Component({
  selector: 'm-web-message-send',
  templateUrl: './web-message-send.component.html',
  styleUrls: ['./web-message-send.component.scss'],
})
export class WebMessageSendComponent extends AddBase implements OnInit {
  constructor(
    private injector: Injector,
    private messageService: WebMessageService,
    public adminService: AdminService,
  ) {
    super(injector);
  }

  all_admin = this.adminService.all_admin();
  messageForm = this.fb.group({
    to: [[], Validators.required],
    title: ['', [Validators.pattern("^[^ ].{0,}$"), Validators.required]],
    content: ['', [Validators.pattern("^[^ ].{0,}$"), Validators.required]],
  });
  selection = new MySelection<AdminModel>('id');

  ngOnInit() {
    this.selection.change.subscribe(() => {
      this.to.setValue(this.selection.keys<number>());
    });
  }

  get to() {
    return this.messageForm.controls.to as FormArray;
  }

  async submit() {
    markAllAsTouched(this.messageForm);
    if (this.messageForm.invalid) {
      return;
    }
    const data = formGroupToFormData(this.messageForm);
    const content = this.messageForm.value.content;
    // 转为html
    const div = document.createElement('div');
    div.innerHTML = marked(content);
    data.set('content_text', div.innerText);
    // blob上传
    const urls = content.match(/blob:http[^\)]+/g) || [];
    for (const url of urls) {
      const blob = await fetch(url).then(resp => resp.blob());
      data.set(url, blob, url);
    }
    await this.messageService.create(data);
    this.back();
  }
}

interface MessageForm {
  to: number[];
  title: string;
  content: string;
  attachment: Blob[];
}
